<template>
  <div>
    <a-card :bordered="false" v-show="!hiddenSearch">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="28">
            <a-col :md="5" :sm="12">
              <a-form-item label="字典名称">
                <a-input v-model="queryParam.dictName" placeholder="请输入字典名称" style="width: 100%"/>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="12">
              <a-form-item label="字典类型">
                <a-input v-model="queryParam.dictType" placeholder="请输入字典类型" style="width: 100%"/>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="12">
              <a-form-item label="状态">
                <a-select v-model="queryParam.status" placeholder="字典状态" style="width: 100%">
                  <a-select-option value="">全部</a-select-option>
                  <a-select-option value="true">正常</a-select-option>
                  <a-select-option value="false">停用</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="7" :sm="18">
              <a-form-item label="创建时间">
                <a-range-picker v-model="queryParam.createDate" @change="onChange" style="width: 100%"></a-range-picker>
              </a-form-item>
            </a-col>
            <a-col :md="1" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-tooltip placement="topLeft" title="查询" arrow-point-at-center>
                  <a-button shape="circle" icon="search" @click="loadDataList"/>
                </a-tooltip>
                <a-tooltip placement="topLeft" title="重置" arrow-point-at-center>
                  <a-button style="margin-left: 8px" @click="() => this.queryParam = {}" icon="sync"/>
                </a-tooltip>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card
      style="margin-top: 10px"
      :bordered="false">
      <div class="table-operator">
        <a-button v-if="dictAddEnable" type="primary" icon="plus-circle" shape="round" @click="$refs.drawer.add()">新建</a-button>
        <a-tooltip placement="topLeft" title="隐藏/显示搜索栏" arrow-point-at-center>
          <a-button size="small" style="position: absolute;right: 55px;top: 30px;" shape="circle" :icon="icon" @click="hiddenSearchMenu(hiddenSearch)"/>
        </a-tooltip>
        <a-button v-show="dictDelEnable && selectedRowKeys.length > 0" type="danger" shape="round" icon="delete" @click="onClick(selectedRowKeys)">删除</a-button>
      </div>
      <a-table
        ref="table"
        row-key="id"
        size="middle"
        @change="change"
        :columns="columns"
        :dataSource="loadData"
        :rowSelection="dictDelEnable ? {selectedRowKeys: selectedRowKeys, onChange: onSelectChange} : null"
        :pagination="pagination"
        @expand="loadInnerData"
        :expandedRowKeys="expandedRowKeys">

        <span slot="status" slot-scope="status">
          <a-tag
            :key="status"
            :color="status === true ? 'green' : 'red'"
          >
            {{ status === true? '正常': '停用' }}
          </a-tag>
        </span>
        <span slot="customActionTitle"><a-icon type="form" :style="{ fontSize: '16px', color: '#4F99FF' }"/>  操作</span>
        <span slot="action" slot-scope="text, record">
          <a v-if="dictEditEnable" @click="handleEdit(record)"><a-icon type="edit"/>  编辑</a>
          <a-divider v-if="dictDelEnable" type="vertical" />
          <a-popconfirm title="真的删除吗?" @confirm="delById(record.id)">
            <a v-if="dictDelEnable"><a-icon type="delete"/>  删除</a>
          </a-popconfirm>
        </span>
        <a-table
          ref="table"
          row-key="id"
          slot="expandedRowRender"
          :columns="innerColumns"
          :data-source="innerData"
          :title="onHeaderCell"
          :pagination="false"
        >
          <span slot="innerActionTitle"><a-icon type="form" :style="{ fontSize: '16px', color: '#4F99FF' }"/>  操作</span>
          <span slot="status" slot-scope="text">
            <a-badge :status="text | statusTypeFilter" :text="text | statusFilter"/>
          </span>
          <span slot="operation" slot-scope="text, record">
            <a v-if="dictEditEnable" @click="dictDataEdit(record)"><a-icon type="edit"/>  编辑</a>
            <a-divider v-if="dictDelEnable" type="vertical" />
            <a-popconfirm title="真的删除吗?" @confirm="delDictDataById(record.id)">
              <a v-if="dictDelEnable"><a-icon type="delete"/>  删除</a>
            </a-popconfirm>
          </span>
        </a-table>
      </a-table>
      <dict-type-modal ref="drawer" @ok="handleOk"/>
      <dict-data-modal ref="dict_data" @ok="handleDictDataOk"/>
    </a-card>
  </div>
</template>

<script>
import { STable } from '@/components'
import { checkPermission } from '@/utils/permissions'
import { dictList, delDictType, dictDataList, delDictData } from '@/api/system'
import message from 'ant-design-vue/es/message'
import DictTypeModal from '../modules/DictTypeModal'
import DictDataModal from '../modules/DictDataModal'
const statusMap = {
  true: {
    status: 'success',
    text: '正常'
  },
  false: {
    status: 'error',
    text: '停用'
  }
}
const innerColumns = [
  { title: '字典标签', dataIndex: 'dictLabel', align: 'center', key: 'dictLabel', width: 120 },
  { title: '字典键值', dataIndex: 'dictValue', align: 'center', key: 'dictValue', width: 120 },
  { title: '字典排序', dataIndex: 'dictSort', key: 'dictSort', align: 'center', width: 120 },
  { title: '状态', dataIndex: 'status', align: 'center', key: 'status', scopedSlots: { customRender: 'status' }, width: 120 },
  { title: '备注', dataIndex: 'remark', align: 'center', ellipsis: true, width: 120 },
  { title: '创建时间', dataIndex: 'createTime', align: 'center', sorter: true, key: 'createTime', width: 200 },
  {
    align: 'center',
    dataIndex: 'operation',
    key: 'operation',
    scopedSlots: { customRender: 'operation' },
    slots: { title: 'innerActionTitle' }
  }
]
const innerData = []
export default {
  name: 'DictList',
  components: {
    STable,
    DictTypeModal,
    DictDataModal
  },
  data () {
    return {
      pagination: {
        total: 1,
        current: 1,
        showTotal: total => `共 ${total} 条 `,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSize: 1
      },
      expandedRowKeys: [],
      expandedRowDictType: null,
      expandedRow: null,
      innerColumns,
      innerData,
      loadData: [],
      showTotal: true,
      // 查询参数
      queryParam: {},
      selectedRowKeys: [],
      selectedRows: [],
      dictAddEnable: checkPermission('system:dict:add'),
      dictDelEnable: checkPermission('system:dict:remove'),
      dictEditEnable: checkPermission('system:dict:edit'),
      dictExportEnable: checkPermission('system:dict:export'),
      hiddenSearch: false,
      icon: 'eye-invisible',
      // 表头
      columns: [
        {
          title: '字典名称',
          dataIndex: 'dictName',
          align: 'center',
          width: 120,
          slots: { title: 'customDictNameTitle' }
        },
        {
          title: '字典类型',
          dataIndex: 'dictType',
          slots: { title: 'customDictTypeTitle' },
          width: 120,
          align: 'center'
        },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' },
          align: 'center',
          width: 120,
          slots: { title: 'customStatusTitle' }
        },
        {
          title: '备注',
          dataIndex: 'remark',
          align: 'center',
          ellipsis: true,
          width: 120,
          slots: { title: 'customRemarkTitle' }
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          sorter: true,
          align: 'center',
          width: 180,
          slots: { title: 'customCreateTimeTitle' }
        }, {
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center',
          width: 120,
          slots: { title: 'customActionTitle' }
        }
      ],
      parameter: {
        pageNum: 1,
        pageSize: 10
      }
    }
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    }
  },
  created () {
    this.loadDataList()
  },
  methods: {
    change (pagination, filters, sorter) { // 对页面大小，筛选，排序等条件修改后重新查询数据
      this.pagination = pagination
      this.parameter.pageNum = pagination.current
      this.parameter.pageSize = pagination.pageSize
      if (sorter.order !== undefined) {
        this.queryParam.sortField = sorter.field.replace(/([A-Z])/g, '_$1').toLowerCase()
        this.queryParam.sortOrder = sorter.order.replace('end', '')
      }
      this.loadDataList()
    },
    loadDataList () {
      this.expandedRowKeys = []
      this.queryParam.pageNum = this.parameter.pageNum
      this.queryParam.pageSize = this.parameter.pageSize
      const requestParameters = Object.assign({}, this.queryParam)
      dictList(requestParameters).then(res => {
          this.loadData = res.data.list
          this.pagination.total = res.data.total
          this.pagination.current = res.data.pageNum
          this.pagination.pageSize = res.data.pageSize
        })
    },
    onHeaderCell (columns) {
      return (
        <div style="text-align:left">
          <a-button icon="plus-circle" type="dashed" onClick={this.dictDataAdd}>新增</a-button>
        </div>
      )
    },
    dictDataEdit (record) {
      this.$refs.dict_data.edit(record)
    },
    dictDataAdd () {
      this.$refs.dict_data.add(this.expandedRowDictType)
    },
    loadInnerData (expanded, record) {
      this.expandedRowKeys = []
      if (expanded) {
        this.expandedRow = record
        this.expandedRowDictType = record.dictType
        this.expandedRowKeys = [record.id]
          dictDataList({ dictType: record.dictType }).then(res => {
            this.innerData = res.data
        })
      }
    },
    handleEdit (record) {
      this.$refs.drawer.edit(record)
    },
    handleOk () {
      this.loadDataList()
    },
    handleDictDataOk () {
      this.loadInnerData(true, this.expandedRow)
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    hiddenSearchMenu (hiddenSearch) {
      this.hiddenSearch = hiddenSearch !== true
      this.icon = this.hiddenSearch === true ? 'eye' : 'eye-invisible'
    },
    onChange (date, dateString) {
      this.queryParam.beginTime = dateString[0]
      this.queryParam.endTime = dateString[1] + ' 23:59:59'
    },
    onClick (ids) {
      const self = this
      this.$confirm({
        title: '你确定删除该字典类型吗?',
        content: h => <div style="color:red;">删除将永久不能恢复</div>,
        onOk () {
          delDictType(ids).then(res => {
            self.$refs.table.refresh()
            message.success('删除字典类型成功')
            self.selectedRowKeys = []
          })
        },
        onCancel () {
          self.selectedRowKeys = []
        }
      })
    },
    delById (id) {
      const ids = [id]
      delDictType(ids).then(res => {
        this.loadDataList()
        message.success('字典类型删除成功')
      }).catch(res => {
        message.error(((res.response || {}).data || {}).message || res.message)
      })
    },
    delDictDataById (id) {
      const ids = [id]
      delDictData(ids).then(res => {
        this.loadInnerData(true, this.expandedRow)
        message.success('字典数据删除成功')
      }).catch(res => {
        message.error(((res.response || {}).data || {}).message || res.message)
      })
    }
  }
}
</script>

<style scoped>

</style>
